import Taro from '@tarojs/taro'
import moment from 'moment'
import { concatWithShopUrl } from '@/utils/ServerUrls'

// 刷新令牌的提前时间
export const LEAD_TIME = 3600 * 12

// TODO url 是否在白名单中
function inWhiteList(url) {
  // 请求白名单，不需要token
  const tokenWhiteList = [
    '/mall/api/v1/customer-login/wechat/miniprogram' // 授权登录
  ]

  for (let i = 0; i < tokenWhiteList.length; i += 1) {
    if (url.indexOf(tokenWhiteList[i]) > -1) return true
  }
  return false
}

/**
 * HTTP 请求
 * @param options
 * @param refresh
 */
let isLoading = false
export default function request(options: Taro.request.Option, refresh = false): Promise<any> {
  if (!isLoading) {
    isLoading = true
    Taro.showLoading({ title: '加载中...', mask: true })
  }
  return new Promise(async (resolve, reject) => {
    if (!inWhiteList(options.url)) {
      // 当前url 不需要token
      const token = Taro.getStorageSync('new_token')
      if (token) {
        options.header = { Authorization: `${token.token_type} ${token.access_token}` }
        if (!refresh) {
          // 如果不是刷新令牌的请求，需要检测令牌的有效性。
          if (moment(token.expiry).unix() > Date.now() / 1000) {
            // 令牌有效
            if (moment(token.expiry).unix() - LEAD_TIME < Date.now() / 1000) {
              // 需要续期
              const newToken = await refreshToken()
              if (newToken) {
                // 存储新令牌
                Taro.setStorageSync('new_token', newToken)
                options.header = { Authorization: `${newToken.token_type} ${newToken.access_token}` }
              }
            }
          } else {
            // console.log(1111111111111111111111111)
            // 需要续期
            const newToken = await refreshToken()
            if (newToken) {
              // 存储新令牌
              Taro.setStorageSync('new_token', newToken)
              options.header = { Authorization: `${newToken.token_type} ${newToken.access_token}` }
            }
          }
        }
      } else {
        // 需要续期
        const newToken = await refreshToken()
        if (newToken) {
          // 存储新令牌
          Taro.setStorageSync('new_token', newToken)
          options.header = { Authorization: `${newToken.token_type} ${newToken.access_token}` }
        }
      }
    }
    // 请求成功后的回调
    options.success = (res) => {
      if (isLoading) {
        isLoading = false
        Taro.hideLoading()
      }
      const { data, statusCode } = res
      if (statusCode === 200) {
        resolve(data)
      } else {
        if (statusCode === 401) {
          const user_name = Taro.getStorageSync('userNames')
          Taro.setStorageSync('userNames', user_name)
          // Taro.reLaunch({ url: '/pages/login/index' })
          Taro.showToast({ title: '会话超时', icon: 'none' })
        }
        if (statusCode === 400) {
          Taro.showToast({ title: data.message, icon: 'none' })
        }
        reject(data)
      }
    }
    // 请求失败后的回调
    options.fail = (res) => {
      if (isLoading) {
        isLoading = false
        Taro.hideLoading()
      }
      reject(res)
    }
    options.url = concatWithShopUrl(options.url)
    Taro.request(options)
  })
}

export async function refreshToken(): Promise<any> {
  return new Promise(async (resolve) => {
    const res = await Taro.login()
    if (res.errMsg === 'login:ok') {
      const params = {
        code: res.code,
        app_id: 'wx5c14f4fce5788216'
      }
      request({ url: '/mall/api/v1/customer-login/wechat/miniprogram', method: 'POST', data: params }, true)
        .then((resu) => {

          if (resu?.data && resu?.data?.expiry && moment(resu.data.expiry).unix() > Date.now() / 1000) {
            resolve(resu.data)
          } else {
            resolve(null)
          }
        })
        .then(() => {
          resolve(null)
        })
    }

  })
}



/**
 * POST 请求
 * @param url
 * @param data
 * @param options
 */
export function POST(url: string, data?: any, options?: object) {
  return request({ url, method: 'POST', data, ...options })
}

